﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ViewCamera.CApVCDisplayCameraEnvelopeApp
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.ViewCamera;

internal sealed class CApVCDisplayCameraEnvelopeApp
{
  public static TxColor DEFAULT_ENVELOPE_COLOR = new TxColor(byte.MaxValue, byte.MaxValue, (byte) 0, 0.4);
  private bool _initialized;
  private bool _registerForDocumentUnloading;
  private Dictionary<TxViewCamera, CApVCDisplayCameraEnvelopeApp.Envelope> _cameraToEnvelopeMap = new Dictionary<TxViewCamera, CApVCDisplayCameraEnvelopeApp.Envelope>();
  private static CApVCDisplayCameraEnvelopeApp _the = (CApVCDisplayCameraEnvelopeApp) null;

  internal static CApVCDisplayCameraEnvelopeApp the()
  {
    if (CApVCDisplayCameraEnvelopeApp._the == null)
      CApVCDisplayCameraEnvelopeApp._the = new CApVCDisplayCameraEnvelopeApp();
    return CApVCDisplayCameraEnvelopeApp._the;
  }

  private CApVCDisplayCameraEnvelopeApp() => this.Initialize();

  public bool HasDisplayedCameraEnvelope(TxViewCamera camera)
  {
    CApVCDisplayCameraEnvelopeApp.Envelope cameraEnvelope = this.GetCameraEnvelope(camera);
    return cameraEnvelope != null && this.IsEnvelopeDisplayed(cameraEnvelope);
  }

  public bool IsEnvelopeDisplayed(CApVCDisplayCameraEnvelopeApp.Envelope envelope)
  {
    return ((TxBaseGeometryCreationObject) envelope.Component).IsValid() && envelope.Component.Visibility == null;
  }

  public CApVCDisplayCameraEnvelopeApp.Envelope GetCameraEnvelope(TxViewCamera camera)
  {
    return this._cameraToEnvelopeMap.ContainsKey(camera) ? this._cameraToEnvelopeMap[camera] : (CApVCDisplayCameraEnvelopeApp.Envelope) null;
  }

  public CApVCDisplayCameraEnvelopeApp.Envelope DisplayCameraEnvelope(TxViewCamera camera)
  {
    CApVCDisplayCameraEnvelopeApp.Envelope envelope = this.GetCameraEnvelope(camera);
    if (envelope == null || !this.IsEnvelopeDisplayed(envelope))
    {
      if (envelope != null)
        this.DestroyCameraEnvelope(camera);
      TxComponent envelopeComponent = this.CreateCameraEnvelopeComponent(camera, CApVCDisplayCameraEnvelopeApp.DEFAULT_ENVELOPE_COLOR, true);
      if (TxComponent.op_Inequality(envelopeComponent, (ITxObject) null))
      {
        envelope = new CApVCDisplayCameraEnvelopeApp.Envelope()
        {
          Component = envelopeComponent,
          Configuration = this.GetRGBDCameraConfiguration(camera)
        };
        this._cameraToEnvelopeMap.Add(camera, envelope);
        this.RegisterToCameraEvents(camera);
      }
    }
    return envelope;
  }

  public void DestroyCameraEnvelope(TxViewCamera camera)
  {
    CApVCDisplayCameraEnvelopeApp.Envelope cameraEnvelope = this.GetCameraEnvelope(camera);
    if (cameraEnvelope == null)
      return;
    if (((TxBaseGeometryCreationObject) cameraEnvelope.Component).IsValid())
      ((TxBaseGeometryCreationObject) cameraEnvelope.Component).Delete();
    this._cameraToEnvelopeMap.Remove(camera);
    this.UnRegisterToCameraEvents(camera);
  }

  public TxComponent CreateCameraEnvelopeComponent(
    TxViewCamera camera,
    TxColor color,
    bool showErrorMsg)
  {
    TxComponent envelopeComponent = (TxComponent) null;
    try
    {
      using (TxLocalComponentCreationData componentCreationData = new TxLocalComponentCreationData($"{camera.Name}_{StringTable.CAMERA_ENVELOPE_NAME_SUFFIX}"))
      {
        componentCreationData.SetAsDisplay();
        envelopeComponent = TxApplication.ActiveDocument.PhysicalRoot.CreateLocalComponent(componentCreationData);
        TxRgbdCameraConfiguration configuration = new TxRgbdViewCamera(camera).Configuration;
        TxRgbdFovAngle rgbFovAngle = configuration.RgbFovAngle;
        int rgbdWidth = configuration.RgbdWidth;
        int rgbdHeight = configuration.RgbdHeight;
        double num1;
        double num2;
        TxRgbdUtils.CalculateHorizontalAndVerticalFovsFromDiagonalFov(rgbFovAngle.AngleInDegrees, (double) rgbdWidth, (double) rgbdHeight, ref num1, ref num2);
        double focalLength = TxRgbdUtils.CalculateFocalLength(rgbFovAngle.AngleInDegrees, (double) rgbdWidth, (double) rgbdHeight);
        double num3 = Math.Tan(num1 / 2.0 * (Math.PI / 180.0)) * focalLength * 2.0;
        double num4 = Math.Tan(num2 / 2.0 * (Math.PI / 180.0)) * focalLength * 2.0;
        double num5 = (double) rgbdWidth / 100.0;
        double num6 = (double) rgbdHeight / 100.0;
        TxPolyline txPolyline1 = (TxPolyline) null;
        using (TxPolylineCreationData polylineCreationData = new TxPolylineCreationData())
        {
          polylineCreationData.SetAsDisplay();
          polylineCreationData.PointsList = new ArrayList()
          {
            (object) new TxVector(-num5 / 2.0, -num6 / 2.0, 0.0),
            (object) new TxVector(num5 / 2.0, -num6 / 2.0, 0.0),
            (object) new TxVector(num5 / 2.0, num6 / 2.0, 0.0),
            (object) new TxVector(-num5 / 2.0, num6 / 2.0, 0.0),
            (object) new TxVector(-num5 / 2.0, -num6 / 2.0, 0.0)
          };
          ((TxObjectCreationData) polylineCreationData).Name = "Rect1";
          txPolyline1 = ((TxBaseGeometryCreationObject) envelopeComponent).CreatePolyline(polylineCreationData);
        }
        TxPolyline txPolyline2 = (TxPolyline) null;
        using (TxPolylineCreationData polylineCreationData = new TxPolylineCreationData())
        {
          polylineCreationData.SetAsDisplay();
          polylineCreationData.PointsList = new ArrayList()
          {
            (object) new TxVector(-num3 / 2.0, -num4 / 2.0, focalLength),
            (object) new TxVector(num3 / 2.0, -num4 / 2.0, focalLength),
            (object) new TxVector(num3 / 2.0, num4 / 2.0, focalLength),
            (object) new TxVector(-num3 / 2.0, num4 / 2.0, focalLength),
            (object) new TxVector(-num3 / 2.0, -num4 / 2.0, focalLength)
          };
          ((TxObjectCreationData) polylineCreationData).Name = "Rect2";
          txPolyline2 = ((TxBaseGeometryCreationObject) envelopeComponent).CreatePolyline(polylineCreationData);
        }
        TxLine txLine = (TxLine) null;
        using (TxLineCreationData lineCreationData = new TxLineCreationData())
        {
          lineCreationData.SetAsDisplay();
          lineCreationData.StartPoint = new TxVector(0.0, 0.0, 0.0);
          lineCreationData.EndPoint = new TxVector(0.0, 0.0, focalLength);
          txLine = ((TxBaseGeometryCreationObject) envelopeComponent).CreateLine(lineCreationData);
        }
        TxSolid txSolid = (TxSolid) null;
        using (TxSolidSweepCreationData sweepCreationData = new TxSolidSweepCreationData())
        {
          sweepCreationData.SetAsDisplay();
          sweepCreationData.AddProfile((ITx1Dimensional) txPolyline1);
          sweepCreationData.AddProfile((ITx1Dimensional) txPolyline2);
          sweepCreationData.GuidingCurve = (ITx1Dimensional) txLine;
          ((TxObjectCreationData) sweepCreationData).Name = "Detection Zone";
          txSolid = ((TxBaseGeometryCreationObject) envelopeComponent).CreateSolidBySweep(sweepCreationData);
          txSolid.Color = color;
        }
        TxTransformation txTransformation = new TxTransformation(camera.AbsoluteLocation.Transform(new TxVector(focalLength / 2.0, 0.0, 0.0)), camera.AbsoluteLocation.RotationEulerZYZ, (TxTransformation.TxRotationType) 2);
        txSolid.AbsoluteLocation = TxTransformation.op_Multiply(txTransformation, new TxTransformation(new TxVector(0.0, Math.PI / 2.0, Math.PI / 2.0), (TxTransformation.TxRotationType) 2));
        txLine.Delete();
        txPolyline1.Delete();
        txPolyline2.Delete();
        envelopeComponent.AttachTo((ITxLocatableObject) camera);
      }
    }
    catch (Exception ex)
    {
      if (showErrorMsg)
      {
        int num = (int) TxMessageBox.Show(string.Format(StringTable.MSG_ERROR_UNABLE_TO_CREATE_CAMERA_ENVELOPE, (object) camera.Name), StringTable.DISPLAY_VIEW_CAMERA_ENVELOPE_CMD_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
      }
      if (TxComponent.op_Inequality(envelopeComponent, (ITxObject) null))
      {
        if (((TxBaseGeometryCreationObject) envelopeComponent).CanBeDeleted)
          ((TxBaseGeometryCreationObject) envelopeComponent).Delete();
      }
    }
    return envelopeComponent;
  }

  public TxRgbdCameraConfiguration GetRGBDCameraConfiguration(TxViewCamera camera)
  {
    return new TxRgbdViewCamera(camera).Configuration;
  }

  public void OnRGBDCameraConfigurationChanged(TxViewCamera camera, bool refreshDisplay = true)
  {
    if (!this.HasDisplayedCameraEnvelope(camera))
      return;
    this.DestroyCameraEnvelope(camera);
    this.DisplayCameraEnvelope(camera);
    if (!refreshDisplay)
      return;
    TxApplication.RefreshDisplay();
  }

  private void Initialize()
  {
    if (this._initialized)
      return;
    this._initialized = true;
    this.RegisterEvents();
    if (!this.IsDataLoaded)
      return;
    this.LoadRuntimeData();
  }

  private void RegisterEvents()
  {
    TxApplication.ApplicationEvents.Exiting += new TxApplication_ExitingEventHandler(this.ApplicationEvents_Exiting);
    TxApplication.DocumentCollection.DocumentLoaded += new TxDocumentCollection_DocumentLoadedEventHandler(this.DocumentCollection_DocumentLoaded);
    TxApplication.DocumentCollection.StudyModeChanging += new TxDocumentCollection_StudyModeChangingEventHandler(this.DocumentCollection_StudyModeChanging);
    TxApplication.DocumentCollection.StudyModeChanged += new TxDocumentCollection_StudyModeChangedEventHandler(this.DocumentCollection_StudyModeChanged);
    if (!this.IsDataLoaded)
      return;
    this.RegisterForDocumentUnloading();
  }

  private void UnregisterEvents()
  {
    TxApplication.ApplicationEvents.Exiting -= new TxApplication_ExitingEventHandler(this.ApplicationEvents_Exiting);
    TxApplication.DocumentCollection.DocumentLoaded -= new TxDocumentCollection_DocumentLoadedEventHandler(this.DocumentCollection_DocumentLoaded);
    TxApplication.DocumentCollection.StudyModeChanging -= new TxDocumentCollection_StudyModeChangingEventHandler(this.DocumentCollection_StudyModeChanging);
    TxApplication.DocumentCollection.StudyModeChanged -= new TxDocumentCollection_StudyModeChangedEventHandler(this.DocumentCollection_StudyModeChanged);
    this.UnregisterForDocumentUnloading();
  }

  private bool IsDataLoaded
  {
    get
    {
      return TxApplication.ActiveDocument != null && TxApplication.ActiveDocument.PlatformGlobalServicesProvider.IsDataLoaded();
    }
  }

  private void RegisterForDocumentUnloading()
  {
    if (this._registerForDocumentUnloading)
      return;
    TxApplication.ActiveDocument.Unloading += new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
    this._registerForDocumentUnloading = true;
  }

  private void UnregisterForDocumentUnloading()
  {
    if (!this._registerForDocumentUnloading)
      return;
    this._registerForDocumentUnloading = false;
    TxApplication.ActiveDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.ActiveDocument_Unloading);
  }

  private void ClearRuntimeData()
  {
    Dictionary<TxViewCamera, CApVCDisplayCameraEnvelopeApp.Envelope>.Enumerator enumerator = this._cameraToEnvelopeMap.GetEnumerator();
    while (enumerator.MoveNext())
    {
      KeyValuePair<TxViewCamera, CApVCDisplayCameraEnvelopeApp.Envelope> current = enumerator.Current;
      TxViewCamera key = current.Key;
      current = enumerator.Current;
      CApVCDisplayCameraEnvelopeApp.Envelope envelope = current.Value;
      if (((TxBaseGeometryCreationObject) envelope.Component).IsValid())
        ((TxBaseGeometryCreationObject) envelope.Component).Delete();
      this.UnRegisterToCameraEvents(key);
    }
    this._cameraToEnvelopeMap.Clear();
  }

  private void LoadRuntimeData()
  {
  }

  private void RegisterToCameraEvents(TxViewCamera camera)
  {
    camera.Deleted += new TxObject_DeletedEventHandler(this.Camera_Deleted);
  }

  private void UnRegisterToCameraEvents(TxViewCamera camera)
  {
    camera.Deleted -= new TxObject_DeletedEventHandler(this.Camera_Deleted);
  }

  private void ApplicationEvents_Exiting(object sender, TxApplication_ExitingEventArgs args)
  {
    this.ClearRuntimeData();
    this.UnregisterEvents();
  }

  private void DocumentCollection_DocumentLoaded(
    object sender,
    TxDocumentCollection_DocumentLoadedEventArgs args)
  {
    this.LoadRuntimeData();
    this.RegisterForDocumentUnloading();
  }

  private void ActiveDocument_Unloading(object sender, TxDocument_UnloadingEventArgs args)
  {
    this.ClearRuntimeData();
    this.UnregisterForDocumentUnloading();
  }

  private void DocumentCollection_StudyModeChanging(
    object sender,
    TxDocumentCollection_StudyModeChangingEventArgs args)
  {
    this.ClearRuntimeData();
  }

  private void DocumentCollection_StudyModeChanged(
    object sender,
    TxDocumentCollection_StudyModeChangedEventArgs args)
  {
    this.LoadRuntimeData();
  }

  private void Camera_Deleted(object sender, TxObject_DeletedEventArgs args)
  {
    TxViewCamera camera = sender as TxViewCamera;
    if (!TxViewCamera.op_Inequality(camera, (ITxObject) null))
      return;
    this.DestroyCameraEnvelope(camera);
  }

  public class Envelope
  {
    public TxComponent Component;
    public TxRgbdCameraConfiguration Configuration;
  }
}
